package kr.saeildamil.androidstudy.ch19;

import kr.saeildamil.androidstudy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class BackWork extends Activity {
	TextView mResult;
	ProgressDialog mPDialog;
	boolean mQuit;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_backwork);
		setProgressBarIndeterminateVisibility(false);

		mResult = (TextView) findViewById(R.id.ch19_backwork_result);
	}

	public void mOnClick(View v) {
		new BackWorkAsyncTask().execute(0, 20);

	}

	class BackWorkAsyncTask extends AsyncTask<Integer, Integer, Integer> {

		@SuppressWarnings("deprecation")
		protected void onPreExecute() {
			super.onPreExecute();
			mPDialog = new ProgressDialog(BackWork.this);
			mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mPDialog.setTitle("Calculatig");
			mPDialog.setMessage("Wait...");
			mPDialog.setCancelable(false);
			mPDialog.setProgress(0);
			mPDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					mQuit = true;
					mPDialog.dismiss();
				}
			});
			mPDialog.show();
		}

		protected Integer doInBackground(Integer... params) {
			int result = 0;
			for (int i = params[0]; i < params[1] + 1; i++) {
				result += i;
				publishProgress(result);
				try {
					Thread.sleep(200);
				} catch (Exception e) {
				}
				if (mQuit) {
					return result;
				}
			}
			return result;
		}

	

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mPDialog.setProgress(values[0]);
			mResult.setText(values[0] + "");
			
		}

		protected void onPostExecute(Integer result) {
			Log.d("ddd", "onPostExecute"+ result);
			super.onPostExecute(result);
			mResult.setText(result + "");
			mPDialog.dismiss();
			mQuit = false;
		}

		protected void onCancelled() {
			super.onCancelled();
			mQuit = false;
		}

	} // end of class BackWorkAsyncTask

}// end of class BackWork
